"""
Nacos 服务发现/注册
"""

import traceback

import requests

from config import settings

CURRENT_SERVER_NAME: str = "MIX"
""" 当前服务名称 """

CURRENT_SERVER_IP: str = "127.0.0.1"
""" 当前服务 IP """

CURRENT_SERVER_PORT: int = 8000
""" 当前服务端口号 """

BEAT_URL: str = (
    f"{{url}}/nacos/v2/ns/health/instance?"
    f"username={{username}}&"
    f"password={{password}}&"
    f"namespaceId={{namespace}}&"
    f"serviceName={{server_name}}&"
    f"ip={{ip}}&"
    f"port={{port}}&"
    f"healthy={{healthy}}"
)

config_dict: dict = {
    "url": settings.NACOS.URL,
    "username": settings.NACOS.USERNAME,
    "password": settings.NACOS.PASSWORD,
    "namespace": settings.NACOS.NAMESPACE,
    "data_id": settings.NACOS.DATA_ID,
    "group": settings.NACOS.GROUP,
}


def server_beat() -> None:
    """
    更新实例健康状态

    - Doc: https://nacos.io/docs/latest/guide/user/open-api/#2.16
    """

    url: str = BEAT_URL.format(
        **config_dict,
        server_name=CURRENT_SERVER_NAME,
        ip=CURRENT_SERVER_IP,
        port=CURRENT_SERVER_PORT,
        healthy="true",
    )

    try:
        res = requests.put(url)

    except:  # noqa
        print(f"[Nacos]更新实例健康状态 错误1 {traceback.format_exc()}")
        return

    data: dict = res.json()

    if data.get("data") != "OK":
        print(f"[Nacos]更新实例健康状态 错误2 {data}")
